package com.example.guiguihomemedical.service.impl;

import com.example.guiguihomemedical.entity.Signing;
import com.example.guiguihomemedical.entity.dto.RecordList;
import com.example.guiguihomemedical.mapper.RecordListMapper;
import com.example.guiguihomemedical.service.RecordListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.guiguihomemedical.entity.Record;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class RecordListServiceImpl implements RecordListService {
    @Autowired
    private RecordListMapper recordListMapper;

    @Override
    public List<RecordList> getRecordList() {
        List<Record> records = recordListMapper.getRecordArgs();
        List<RecordList> recordLists = new ArrayList<>();
        Integer recordTotal=recordListMapper.getRecordTotal();
        for (Record record : records) {
//    计算年龄
            String idcard=record.getIdcard();
            String birthdayString=idcard.substring(6,14);
            LocalDate birthday=LocalDate.parse(birthdayString, DateTimeFormatter.ofPattern("yyyyMMdd"));
            Integer age = calculateAge(birthday,LocalDate.now());

//    获取签约状态
            Signing signing = recordListMapper.getEndTimeById(record.getIdcard());
            Integer status = 0;
            if (signing != null) {
                LocalDateTime now = LocalDateTime.now();
                Instant instant = signing.getEndtime().toInstant();
                ZoneId zoneId = ZoneId.systemDefault();
                LocalDateTime endTime = instant.atZone(zoneId).toLocalDateTime();
                if (now.isAfter(endTime)) {
                    status = 2;
                } else {
                    status = 1;
                }
            }
            List<String> listenerNames = recordListMapper.getListenerNamesById(record.getIdcard());
            RecordList recordList = new RecordList(
                    record.getIdcard(),
                    record.getName(),
                    record.getSex(),
                    age,
                    record.getDetailedresidence(),
                    listenerNames,
                    record.getPhone(),
                    status,
                    recordTotal,
                    recordTotal
            );
            recordLists.add(recordList);
        }


        return recordLists;
    }

    private Integer calculateAge(LocalDate birthday, LocalDate currentday) {
        int age = currentday.getYear() - birthday.getYear();
        if (currentday.getMonthValue() < birthday.getMonthValue() || currentday.getMonthValue() == currentday.getMonthValue() && currentday.getDayOfMonth() < birthday.getDayOfMonth()) {
            age--;
        }
        return age;
    }
}
